﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using crm_dal.Objects;

namespace crm_services.WCF.MakeASale
{



	[ServiceBehavior(Namespace = "http://crm_services/wcf/MakeASale/MakeASale.svc")]
	public class MakeASale : IMakeASale
	{
		#region IMakeASale Members

		public MakeASaleResponse MakeSale(MakeASaleRequest request)
		{
			DBHandler.Init();
			var response = new MakeASaleResponse 
								{
									Success = true,
									IsError = false,
									ErrorMessage = ""
								};

			try
			{
				var client = request.TheClient;
				if (client.ClientID < 0)
				{
					client.ClientID = client.GetNextPKValue();
					client.Create();
				}
				else
				{
					client.Update();
				}


				var sale = request.TheSale;

				sale.SaleID = sale.GetNextPKValue();
				sale.ClientID = client.ClientID;
				sale.ProductID = Product.GetAll().First().ProductID;
				sale.Create();

				foreach (var item in sale.SaleItems)
				{
					item.SaleID = sale.SaleID;
					item.Create();
				}

				

			}
			catch (Exception ex)
			{
				response.Success = false;
				response.IsError = true;
				response.ErrorMessage = ex.Message;
			}


			return response;
		}



		#endregion IMakeASale Members
	}
}
